package cn.qicaiwang.open.admin.controller.system;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.qicaiwang.open.common.annotation.Log;
import cn.qicaiwang.open.common.annotation.RepeatSubmit;
import cn.qicaiwang.open.common.enums.BusinessType;
import cn.qicaiwang.open.common.enums.ResultStatusCodeEnum;
import cn.qicaiwang.open.common.response.ResponseResult;
import cn.qicaiwang.open.common.utils.SecurityUtil;
import cn.qicaiwang.open.system.model.dto.SystemDictItemDTO;
import cn.qicaiwang.open.system.model.entity.SystemDictItem;
import cn.qicaiwang.open.system.model.req.SystemDictItemREQ;
import cn.qicaiwang.open.system.service.ISystemDictItemService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 字典项管理
 */
@Slf4j
@RestController
@RequestMapping("system/dict/item")
public class SystemDictItemController {
    @Autowired
    private ISystemDictItemService systemDictItemService;

    /**
     * 分页查询字典项
     * @param page
     * @param params
     * @return
     */
    @GetMapping(value = "page")
    @Log(title = "字典项管理", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('system:dictitem:page')")
    public ResponseResult page(Page page, SystemDictItemREQ params) {
        Page<SystemDictItem> pageList = systemDictItemService.pageList(page, params);
        return ResponseResult.ok(pageList);
    }

    /**
     * 删除字典项
     * @param id
     * @return
     */
    @RepeatSubmit
    @GetMapping("delete/{id}")
    @Log(title = "字典项管理", businessType = BusinessType.DELETE)
    @PreAuthorize("@permission.hasPermission('system:dictitem:delete')")
    public ResponseResult delete(@PathVariable String id){
        if(StrUtil.isBlank(id)){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        boolean b = systemDictItemService.removeById(id);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 字典项详情
     * @param id
     * @return
     */
    @GetMapping("get/{id}")
    @Log(title = "字典项管理", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('system:dictitem:get')")
    public ResponseResult get(@PathVariable String id){
        if(StrUtil.isBlank(id)){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        SystemDictItem systemDictItem = systemDictItemService.getById(id);
        if(systemDictItem != null){
            return ResponseResult.ok(systemDictItem);
        }
        return ResponseResult.error(ResultStatusCodeEnum.DATA_NO_EXIST);
    }

    /**
     * 添加字典项
     * @param systemDictItemDTO
     * @return
     */
    @RepeatSubmit
    @PostMapping("add")
    @Log(title = "字典项管理", businessType = BusinessType.INSERT)
    @PreAuthorize("@permission.hasPermission('system:dictitem:add')")
    public ResponseResult add(@RequestBody SystemDictItemDTO systemDictItemDTO){
        String userId = SecurityUtil.getUserId();
        if(systemDictItemDTO == null || StrUtil.isBlank(systemDictItemDTO.getTypeId())){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        SystemDictItem systemDictItem = new SystemDictItem();
        BeanUtils.copyProperties(systemDictItemDTO, systemDictItem);
        systemDictItem.setId(IdUtil.getSnowflakeNextIdStr());
        systemDictItem.setCreateBy(userId);
        systemDictItem.setCreateTime(new Date());

        boolean b = systemDictItemService.save(systemDictItem);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 修改字典项
     * @param systemDictItemDTO
     * @return
     */
    @RepeatSubmit
    @PostMapping("update")
    @Log(title = "字典项管理", businessType = BusinessType.UPDATE)
    @PreAuthorize("@permission.hasPermission('system:dictitem:update')")
    public ResponseResult update(@RequestBody SystemDictItemDTO systemDictItemDTO){
        String userId = SecurityUtil.getUserId();
        if(systemDictItemDTO == null || StrUtil.isBlank(systemDictItemDTO.getId()) || StrUtil.isBlank(systemDictItemDTO.getTypeId())){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        SystemDictItem systemDictItem = new SystemDictItem();
        BeanUtils.copyProperties(systemDictItemDTO, systemDictItem);
        systemDictItem.setUpdateBy(userId);
        systemDictItem.setUpdateTime(new Date());

        boolean b = systemDictItemService.updateById(systemDictItem);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 根据字典类型查询字典项
     * @param dictType
     * @return
     */
    @GetMapping("query/{dictType}")
    @Log(title = "字典项管理", businessType = BusinessType.SELECT)
    public ResponseResult query(@PathVariable String dictType){
        if(StrUtil.isBlank(dictType)){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        List<SystemDictItem> list = systemDictItemService.selectListByDictType(dictType);
        return ResponseResult.ok(list);
    }

    /**
     * 根据字典类型查询字典项
     * @param dictTypes
     * @return
     */
    @PostMapping("queryBatch")
    @Log(title = "字典项管理", businessType = BusinessType.SELECT)
    public ResponseResult queryBatch(@RequestBody String[] dictTypes){
        if(dictTypes == null || dictTypes.length <= 0){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        for (String dictType : dictTypes) {
            List<SystemDictItem> list = systemDictItemService.selectListByDictType(dictType);
            result.put(dictType, list);
        }
        return ResponseResult.ok(result);
    }




    /**
     * 回收站
     * @param page
     * @return
     */
    @GetMapping(value = "recyclebin")
    @Log(title = "字典项管理", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('system:dictitem:recyclebin')")
    public ResponseResult recyclebin(Page page) {

        Page<SystemDictItem> pageList = systemDictItemService.recyclebin(page);
        return ResponseResult.ok(pageList);
    }

    /**
     * 还原
     * @param ids
     * @return
     */
    @PostMapping(value = "restore")
    @Log(title = "字典项管理", businessType = BusinessType.UPDATE)
    @PreAuthorize("@permission.hasPermission('system:dictitem:restore')")
    public ResponseResult restore(@RequestBody List<String> ids) {
        if(ids == null || ids.size() <= 0){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        Boolean b = systemDictItemService.restore(ids);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 清空回收站
     * @return
     */
    @GetMapping(value = "clear")
    @Log(title = "字典项管理", businessType = BusinessType.DELETE)
    @PreAuthorize("@permission.hasPermission('system:dictitem:clear')")
    public ResponseResult clear() {
        Boolean b = systemDictItemService.clear();
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }
}
